<template>
  <!-- 容器类：行布局 -->
  <FcLayoutRow
    v-if="node.type === 'FcLayoutRow'"
    :gap="node.props?.gap || 0"
    :col="node.props?.col || [24]"
  >
    <template #default="{ index }">
      <RenderNode
        v-if="node.children && node.children[index]"
        :node="node.children[index]"
        :model-value="formData"
        @update:model-value="formData = $event"
      />
    </template>
  </FcLayoutRow>

  <!-- 叶子类：控件（可按需扩展） -->
  <template v-else>
    <el-form-item :label="node.label" :prop="node.name" v-if="showExpression">
      <component
        :is="leafComponentName"
        v-model="formData[node.name]"
        v-bind="leafProps"
      />
    </el-form-item>
  </template>
</template>

<script setup name="RenderNode">
import jsonLogic from "json-logic-js";

import { inject,computed,defineAsyncComponent,h } from "vue";
import FcLayoutRow from "@fc/components/FcLayoutRow/FcLayoutRow.vue";
import FcLoadError from "@fc/components/FcLoadError/FcLoadError.vue";

const props = defineProps({
  node: { type: Object, required: true },
  modelValue: { type: Object, required: true },
});
const emit = defineEmits(["update:modelValue"]);

// 全局注册器
const formRenderControl = inject("formRenderControl");

const formData = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});


// 创建动态组件
function createAsyncComponent({id,type}) {
  let dynamicComponent=defineAsyncComponent({
    loader: async () => {
      try {
        // 尝试导入组件
        const module = await import(`@fc/components/${type}/${type}.vue`);
        console.log(`组件类型${type}：${id} 加载成功`);
        return module.default||module;
      } catch (error) {
        console.error(`组件类型${type}：${id} 加载失败:`,typeof error);
        return {
          name: 'AsyncComponentError',
          render() {
            return h(FcLoadError, {
                componentType: type,
                componentId: id,
                errorMessage: error.message,
                errorDetails: error.stack
            })
          }
        }
      }
    },
    loadingComponent: { template: '<div>加载中...</div>' },
    errorComponent: { template: '<div>加载失败</div>' },
    delay: 200,
    timeout: 1000
  })
  return dynamicComponent;
}


// 动态组件名称
const leafComponentName = computed(() => {
  let {id,type}=props.node
  return createAsyncComponent({id,type})
});

// 增强事件处理器，增加上下文
const enhanceEvents = (node) => {
  let events=node.events||{};
  let newEvents={}  
  if(Object.keys(events).length>0){
    for(let key in events){
      newEvents[key]=(...args)=>{
        events[key](...args,node,formRenderControl)
      }
    }
  }
  return newEvents;
}

// 组件属性
const leafProps = computed(() => {
  const p = {...props.node.props,...props.node.commonProps} || {};
  let events=props.node.events||{};
  if(Object.keys(events).length>0){
    p.events=enhanceEvents(props.node)
  }
  return p;
});

//  组件事件
const leafEvents = computed(() => {
  const e = props.node.events || {};
  return e;
});

// 显隐表达式
const showExpression = computed(() => {
  const showExpression = props.node?.commonProps?.showExpression || "";
  if (showExpression) {
    const result = jsonLogic.apply(showExpression, formData.value);
    return result;
  }
  return true;
});

</script>

<style scoped></style>
